"""
http://baostock.com/baostock/index.php/证券基本资料

create table st_cn_stock_industry_w (
    dt date not null comment '日期',
    stock_code varchar(20) not null default '' comment '股票代码',
    stock_name varchar(30) not null default '' comment '股票中文名',
    industry varchar(30) comment '行业',
    industry_category varchar(30) comment '行业分类',
    PRIMARY KEY (dt, stock_code),
    KEY index_dt (dt)
) ENGINE=InnoDB COMMENT='A股证券行业分类表'
"""

from common import Args, StockApi, Database
import sys


args = Args.parse()
api = StockApi()
db = Database()

dt = args.date
fields_map = {
    'updateDate': 'dt',
    'code': 'stock_code',
    'code_name': 'stock_name',
    'industry': 'industry',
    'industryClassification': 'industry_category'
}

exist_sql = '''
select count(1) cnt from st_cn_stock_industry_w
where dt=%s
and stock_code=%s
'''


# {'updateDate': '2024-03-18', 'code': 'sz.301519', 'code_name': '舜禹股份', 'industry': None, 'industryClassification': '申万一级行业'}

data = []

for row in api.query_stock_industry(fields_map=fields_map):
    # 如果已经存在则跳过
    stock_code = row['stock_code']
    dt = row['dt']
    cnt = db.execute(exist_sql, (dt, stock_code))[0]['cnt']
    if cnt > 0:
        print(f'{stock_code} {dt} is ready done.')
        continue

    print('processing:', row)
    data.append(row)

if data:
    db.write('st_cn_stock_industry_w', data)

print('st_cn_stock_industry_w done')

